package com.eastfair.home.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
//import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eastfair.boot.service.SuperServiceImpl;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.exception.BizException;
import com.eastfair.home.dao.DrawingMapper;
import com.eastfair.home.dto.DrawingDTO;
import com.eastfair.home.entity.Drawing;
import com.eastfair.home.service.DrawingService;
import com.eastfair.home.service.ExhibitionDrawingService;
import com.eastfair.home.vo.DrawingVO;
import com.eastfair.venueservice.consts.CommonConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 业务实现类
 * 图纸表
 * </p>
 *
 * @author lyw
 * @date 2022-08-01
 */
@Slf4j
@Service
//@DS("#thread.tenant")
public class DrawingServiceImpl extends SuperServiceImpl<DrawingMapper, Drawing> implements DrawingService {

    private static final String DRAWING_DRAWING_TYPE = "0";

    private static final String MATERIAL_DRAWING_TYPE = "1";

    private static final String PUBLIC_DRAWING_TYPE = "2";

    @Resource
    private ExhibitionDrawingService exhibitionDrawingService;

    @Resource
    private DrawingMapper drawingMapper;

    /**
     * 处理逻辑删除相关处理
     *
     * @param modelList 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerRemoveByIdsOfLogic(Collection<Drawing> modelList) {
        modelList.forEach(s -> s.setIsDeleted(BusinessConstant.YES));
        return R.successDef();
    }

    @Override
    protected R<Boolean> handlerSave(Drawing model) {
        model.setProjectId(ContextUtil.getProjectId());
        model.setSubsystemId(ContextUtil.getSubSystemId());
        return R.successDef();
    }

    @Override
    public List<DrawingVO> listDrawingVO(DrawingDTO drawingDTO) {
        log.info("listDrawingVO - 查询图纸列表VO, params={}", JSONObject.toJSON(drawingDTO));
        QueryWrapper<Drawing> queryWrapper = createDrawingVOQueryWrapper(drawingDTO);
        return drawingMapper.listDrawingVO(queryWrapper);
    }

    @Override
    public List<Drawing> listDrawing(DrawingDTO drawingDTO) {
        log.info("listDrawing - 查询图纸列表, params={}", JSONObject.toJSON(drawingDTO));
        QueryWrapper<Drawing> queryWrapper = createDrawingQueryWrapper(drawingDTO);
        return this.list(queryWrapper);
    }

    @Override
    public List<DrawingVO> listDrawingVOForReportSpace(DrawingDTO drawingDTO) {
        log.info("listDrawingForReportSpace - 查询图纸列表为搭建商报馆, drawingDTO={}", drawingDTO);
        QueryWrapper<Drawing> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .eq("d.is_deleted", BusinessConstant.DELETE_NO)
                .eq("d.is_enabled", BusinessConstant.ENABLE_YES)
                .eq(drawingDTO.getExhibitionId() != null, "ed.exhibition_id", drawingDTO.getExhibitionId())
                .eq(drawingDTO.getHomeId() != null, "d.home_id", drawingDTO.getHomeId())
                .and(drawingTypeQuery -> drawingTypeQuery
                        .eq("d.drawing_type", PUBLIC_DRAWING_TYPE)
                        .or(drawingDTO.getIsDouble() != null, isDoubleQuery -> isDoubleQuery.eq("d.is_double", drawingDTO.getIsDouble()))
                        .or(drawingDTO.getIsPoint() != null, isPointQuery -> isPointQuery.eq("d.is_point", drawingDTO.getIsPoint())))
                .orderByAsc("d.sort")
        ;
        return drawingMapper.listDrawingVOForReportSpace(queryWrapper);
    }

    @Override
    public List<Drawing> listDrawingByHomeId(Long homeId) {
        DrawingDTO param = new DrawingDTO();
        param.setHomeId(homeId);
        return listDrawing(param);
    }

    @Override
    public DrawingVO getDrawingVOById(Long id) {
        log.info("getDrawingVOById - id获取图纸详情, id={}", id);
        Drawing drawing = getById(id);
        if (drawing == null) {
            return null;
        }
        return BeanUtil.toBean(drawing, DrawingVO.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveDrawing(DrawingDTO drawingDTO) {
        log.info("saveDrawing - 保存图纸, params={}", JSONObject.toJSON(drawingDTO));
        if (PUBLIC_DRAWING_TYPE.equals(drawingDTO.getDrawingType())) {
            drawingDTO.setIsDouble(null);
            drawingDTO.setIsPoint(null);
        }
        if (DRAWING_DRAWING_TYPE.equals(drawingDTO.getDrawingType())) {
            drawingDTO.setIsPoint(null);
        }
        if (MATERIAL_DRAWING_TYPE.equals(drawingDTO.getDrawingType())) {
            drawingDTO.setIsDouble(null);
        }
        Drawing drawing = BeanUtil.toBean(drawingDTO, Drawing.class);
        return this.save(drawing);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateDrawing(DrawingDTO drawingDTO) {
        log.info("updateDrawing - 修改图纸, params={}", JSONObject.toJSON(drawingDTO));
        Drawing drawing = getById(drawingDTO.getId());
        if (drawing == null) {
            throw BizException.wrap(-1, "图纸不存在");
        }
        // 更新默认值
        if (PUBLIC_DRAWING_TYPE.equals(drawingDTO.getDrawingType())) {
            drawing.setIsDouble(null);
            drawing.setIsPoint(null);
        }
        if (DRAWING_DRAWING_TYPE.equals(drawingDTO.getDrawingType())) {
            drawing.setIsPoint(null);
        }
        if (MATERIAL_DRAWING_TYPE.equals(drawingDTO.getDrawingType())) {
            drawing.setIsDouble(null);
        }
        updateAllById(drawing);
        // 更新指定值
        CopyOptions copyOptions = CopyOptions
                .create()
                .setIgnoreProperties(CommonConstants.COMMON_IGNORE_PROPERTIES);
        BeanUtil.copyProperties(drawingDTO, drawing, copyOptions);
        drawing.setIsEnabled(drawingDTO.getIsEnabled());
        return updateById(drawing);
    }

    @Override
    public Boolean delDrawing(Long id) {
        log.info("delDrawing - 修改图纸, params={}", id);
        // 删除图纸
        Drawing drawing = Drawing
                .builder()
                .id(id)
                .isDeleted(BusinessConstant.DELETE_YES)
                .build();
        this.updateById(drawing);
        // 删除展会图纸
        return exhibitionDrawingService.removeByDrawingId(id);
    }

    private QueryWrapper<Drawing> createDrawingQueryWrapper(DrawingDTO drawingDTO) {
        QueryWrapper<Drawing> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(Drawing::getIsDeleted, BusinessConstant.DELETE_NO)
                .eq(drawingDTO.getHomeId() != null, Drawing::getHomeId, drawingDTO.getHomeId())
                .like(StrUtil.isNotBlank(drawingDTO.getDrawingName()), Drawing::getDrawingName, drawingDTO.getDrawingName())
                .eq(StrUtil.isNotBlank(drawingDTO.getDrawingType()), Drawing::getDrawingType, drawingDTO.getDrawingType())
                .eq(drawingDTO.getIsEnabled() != null, Drawing::getIsEnabled, drawingDTO.getIsEnabled())
                .eq(drawingDTO.getIsDouble() != null, Drawing::getIsDouble, drawingDTO.getIsDouble())
                .eq(drawingDTO.getIsPoint() != null, Drawing::getIsPoint, drawingDTO.getIsPoint())
                .orderByAsc(Drawing::getSort);
        return queryWrapper;
    }

    private QueryWrapper<Drawing> createDrawingVOQueryWrapper(DrawingDTO drawingDTO) {
        QueryWrapper<Drawing> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .eq("d.is_deleted", BusinessConstant.DELETE_NO)
                .eq(drawingDTO.getHomeId() != null, "d.home_id", drawingDTO.getHomeId())
                .eq(drawingDTO.getExhibitionId() != null, "ed.exhibition_id", drawingDTO.getExhibitionId())
                .like(StrUtil.isNotBlank(drawingDTO.getDrawingName()), "d.drawing_name", drawingDTO.getDrawingName())
                .eq(StrUtil.isNotBlank(drawingDTO.getDrawingType()), "d.drawing_type", drawingDTO.getDrawingType())
                .eq(drawingDTO.getIsEnabled() != null, "d.is_enabled", drawingDTO.getIsEnabled())
                .eq(drawingDTO.getIsDouble() != null, "d.is_double", drawingDTO.getIsDouble())
                .eq(drawingDTO.getIsPoint() != null, "d.is_point", drawingDTO.getIsPoint())
                .groupBy("d.id")
                .orderByAsc("d.sort");
        return queryWrapper;
    }

}
